package pdm.traj.service.impl;

import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import pdm.traj.entity.PartInfo;
import pdm.traj.entity.TrackPoint2;
import pdm.traj.service.KeyService;
import pdm.traj.service.PartService;
import pdm.traj.service.UpdateService;
//import pdm.traj.service.impl.TrajDataServiceImpl.CheckUpdateState;
import pdm.traj.update.UpdateTrajSync;

public class UpdateServiceSyncImpl implements UpdateService {
	private final Log log = LogFactory.getLog(UpdateServiceSyncImpl.class);
	private static final Integer m1 = new Integer(-1);
	
	private PartService partService;
	private KeyService keyService;
	
	private Map<Integer, UpdateTrajSync> updateTrajs;
	
	public void init() {
		updateTrajs = new Hashtable<Integer, UpdateTrajSync>();
		List<PartInfo> piList = partService.getAllPartInfo();
		for (PartInfo pi : piList) {
			Integer index = partService.getPIIndexByPartInfo(pi);
			if (!index.equals(m1)) {
				try {
					UpdateTrajSync updateTraj = new UpdateTrajSync(index, pi.getIp(), Integer.parseInt(pi.getPort()));
					updateTraj.setKeyService(keyService);
					updateTrajs.put(index, updateTraj);
				} catch (NumberFormatException nfe) {
					nfe.printStackTrace();
				}
			}
		}
	}
	
	@Override
	public int update(TrackPoint2 tp) {		
		Integer index = partService.getPIIndexByTP(tp);
		if (!index.equals(m1)) {
			updateTrajs.get(index).update(tp);
		}
		return 1;
	}

	public void setPartService(PartService partService) {
		this.partService = partService;
	}

	public void setKeyService(KeyService keyService) {
		this.keyService = keyService;
	}
	
	

}
